<template>
	<view>
		<view v-if="infos.length > 0">
			<nav-bar :title="title" :isBack="false"></nav-bar>
			<view class="share">
				<button open-type="share" class="btn">去分享</button>
			</view>
			<view class="bg">
				<image :src="STATIC_URL + 'dlbj.png'" mode="widthFix" class="bg-img"></image>
				<view class="info-card">
					<view :class="{'status': true, 'open': openStatus === '已开通'}">{{openStatus}}</view>
					<view :class="{'info': true, 'partner': current === 1}">
						<view class="left">
							<view class="name">{{showInfo.vip_name}}</view>
							<block v-if="current === 0">
								<block v-if="openStatus==='已开通'">
									<view class="time" v-if="userInfo.is_partner !== 1">会员将在{{userInfo.end_vip_time}}到期
									</view>
									<view class="time" v-else>已开通终身VIP会员,畅享奥莱奢品特权</view>
								</block>
								<view class="time" v-else>{{showInfo.vip_desc}}</view>
							</block>
							<block v-if="current === 1">
								<view class="time" v-if="userInfo.is_partner === 1">已开通终身{{showInfo.vip_name}},畅享奥莱奢品特权
								</view>
								<view class="time" v-else>{{showInfo.vip_desc}}</view>
							</block>
						</view>
						<view class="icon">
							<image :src="STATIC_URL_PATH + '/vip/head-icon1.png'" mode="aspectFit" v-if="current === 0">
							</image>
							<image :src="STATIC_URL_PATH + '/vip/head-icon2.png'" mode="aspectFit" v-else></image>
						</view>
					</view>
					<view class="bg">
						<image :src="STATIC_URL_PATH + '/vip/vip-bg.png'" mode="aspectFit" v-if="current === 0"></image>
						<image :src="STATIC_URL_PATH + '/vip/partner-bg.png'" mode="aspectFit" v-else></image>
					</view>
				</view>
			</view>
			<!-- <view class="tabs">
				<view :class="{'item': true, 'active': current === index}" @click="changeTab(index)"
					v-for="(item, index) in tabs" :key="index">
					{{item.name}}
				</view>
			</view> -->
			<view class="intro-title" v-if="">
				<view class="title">
					开通享<text style="font-weight: bold;margin: 0 5rpx;">{{showInfo.interest.length}}</text>大权益
				</view>
			</view>
			<view class="intro-list">
				<view class="item" v-for="(item, index) in showInfo.interest" :key="index" @click="openDetail(item)">
					<image :src="item.image" mode="aspectFit"></image>
					<text class="name">{{item.interest_name}}</text>
					<text class="intro">{{item.interest_desc}}</text>
				</view>
			</view>
			<block>
				<view class="target">
					<view class="item" v-for="(item, index) in payTarget" :key="index" @click="changeTarget(item.type)">
						<view :class="{'circle': true, 'checked': item.type == target}"></view>
						<text>{{item.name}}</text>
					</view>
				</view>
				<view class="button" @click="paymentConfirm">{{btnName}}</view>
				<view class="discount">
					<view class="open-coupon" @click="showDiscount = true" v-if="vipCoupon && current === 0">
						<view class="dot"></view>
						<image :src="`${STATIC_URL2}coupon.png`" mode="aspectFit" />
						<text>已减¥{{vipCoupon.coupon_denomination}} 查看优惠明细</text>
					</view>
					<view class="open-coupon" @click="showDiscount = true" v-if="current === 0 && integralNum > 0">
						<view class="dot"></view>
						<image :src="`${STATIC_URL2}integral.png`" mode="aspectFit" />
						<text>已减¥{{integralNum}} 查看使用明细</text>
					</view>
				</view>
				<view class="agreement" @click="agreement = !agreement">
					<u-icon name="checkmark-circle-fill" v-if="agreement" color="#CB712B"></u-icon>
					<u-icon name="checkmark-circle" v-else></u-icon>
					<text>购买即视为同意</text>
					<text class="link" @click.stop="openAgreement">《{{tabs[current].name}}服务协议》</text>
				</view>
				<view style="height: 50rpx;"></view>
			</block>
			<block v-if="showInfo.coupon && openStatus==='已开通'">
				<view class="legal-title">可领权益</view>
				<view class="coupon-group">
					<coupon-item class="item" @clickBtn="recive" :info="item" v-for="(item, index) in showInfo.coupon"
						:key="index"></coupon-item>
				</view>
			</block>
			<modal :value.sync="show" @confirm="setPhone"></modal>
			<recive-modal :value.sync="showRecive" @confirm="openCoupon"></recive-modal>
			<discountInfo :value.sync="showDiscount" :coupon="vipCoupon" :info="showInfo" :total="vipPrice"
				:integralNum="integralNum"></discountInfo>

		</view>
		<pageCont />
	</view>
</template>
<script>
	import navBar from '@/components/navBar/navBar.vue'
	import time from "@/utils/time.js"
	import introList from './data.json'
	import couponItem from './components/coupon-item.vue'
	import {
		vipInfoApi,
		openVipApi
	} from '@/api/my.js'
	import {
		reciveCouponApi,
		vipCounponApi
	} from "@/api/coupon.js"
	import {
		mapGetters,
		mapState,
		mapActions
	} from 'vuex'
	import modal from './components/modal.vue'
	import reciveModal from './components/reciveModal.vue'
	import discountInfo from './components/discountInfo.vue'
	import pageCont from '@/components/pageContainer.vue'
	export default {
		components: {
			couponItem,
			modal,
			reciveModal,
			discountInfo,
			pageCont
		},
		data() {
			return {
				current: 0,
				tabs: [{
						name: 'SVIP权益'
					},
					{
						name: '合伙人'
					}
				],
				target: 1,
				payTarget: [{
						name: '送给自己',
						type: 1
					},
					{
						name: '送给朋友',
						type: 2
					},
				],
				infos: [],
				phone: "",
				show: false,
				showRecive: false,
				agreement: true,
				showDiscount: false,
				vipCoupon: null
			}
		},
		computed: {
			...mapGetters(['userInfo']),
			...mapState('common', ['config']),
			title() {
				let str = `${this.tabs[this.current].name}权益`
				return str
			},
			integralNum() {
				let num = 0
				if (this.userInfo) {
					let max = Math.floor(this.showInfo.vip_price * this.config.gold_proportion)
					let gold = this.userInfo.gold_num
					num = gold < max ? gold : max
				}
				if (this.vipCoupon && num >= this.showInfo.vip_price) {
					let off = parseFloat(this.vipCoupon.coupon_denomination)
					num -= off
				}
				return num
			},
			timeArea() {
				let date = new Date()
				let stamp = date.getTime() / 1000
				let start = time.formatTime(stamp, 'Y.M.D')
				let end = start.split('.').map((item, index) => {
					if (index === 0) {
						return parseInt(item) + 1
					}
					return item
				}).join(".")
				return `${start}-${end}`
			},
			list() {
				let list = []
				if (this.current === 0) {
					list = introList.vipIntro
				} else {
					list = introList.partnerIntro
				}
				return list
			},
			showInfo() {
				if (this.infos.length > 0) {
					return this.infos[this.current]
				} else {
					return {}
				}
			},
			openStatus() {
				let flag = false;
				if (!this.userInfo) return '未开通'
				// 合伙人直接就是会员
				if (this.userInfo.is_partner === 1) {
					return '已开通'
				}
				// VIP会员逻辑
				if (this.current === 0) {
					let endTime = new Date(this.userInfo.vip_expiration_time * 1000).getTime()
					flag = endTime > new Date().getTime()
				} else {
					// 合伙人逻辑
					flag = this.userInfo.is_partner === 1
				}
				return flag ? '已开通' : '未开通'
			},
			btnName() {
				// {{showInfo.vip_price}}{{showInfo.company}}
				// 合伙人
				if (this.userInfo.is_partner === 1 && this.current === 1 && this.target === 1) {
					return '您已开通合伙人权益'
				} else {
					// if (this.current === 0 && this.vipCoupon) {
					// 	let price = parseFloat(this.showInfo.vip_price)
					// 	let off = parseFloat(this.vipCoupon.coupon_denomination)
					// 	return `${price - off}${this.showInfo.company}`
					// } else {
					// 	return `${this.showInfo.vip_price}${this.showInfo.company}`
					// }
					return `${this.vipPrice}${this.showInfo.company}`
				}
			},
			vipPrice() {
				let total = 0
				if (this.vipCoupon && this.current === 0) {
					let price = parseFloat(this.showInfo.vip_price)
					let off = parseFloat(this.vipCoupon.coupon_denomination)
					total = (price - off).toFixed(2)
				} else {
					total = this.showInfo.vip_price
				}
				total -= this.integralNum
				return total.toFixed(2)
			}
		},
		onLoad(opt) {
			if (!this.$utils.storage.get("token")) {
				// 请先登录
				setTimeout(() => {
					this.$Router.push('/pages/login/index')
				}, 100)
				return
			}
			this.current = opt.type - 1 || 0
		},
		onShow() {
			this.getData()
		},
		methods: {
			...mapActions([
				"setUserInfo",
			]),
			changeTab(index) {
				this.current = index
			},
			changeTarget(type) {
				this.target = type
			},
			setPhone(phone) {
				this.payment({
					phone
				})
			},
			openAgreement() {
				uni.navigateTo({
					url: `/pages/common/agreement/agreement?type=${this.current + 1}`
				})
			},
			openCoupon() {
				uni.navigateTo({
					url: '/pages/mine/coupon/coupon'
				})
			},
			async getData() {
				let {
					data
				} = await vipInfoApi()
				// this.vipInfo = data[0]
				// this.partnerInfo = data[1]
				this.infos = data
				this.getVipCoupon()
			},
			async getVipCoupon() {
				let {
					data
				} = await vipCounponApi({
					price: this.showInfo.vip_price
				})
				if (data) {
					this.vipCoupon = data
				}
			},
			paymentConfirm() {
				if (this.userInfo.is_partner && this.target === 1) {
					return uni.showToast({
						icon: 'none',
						title: '您已享有全部权益，无需重复开通'
					})
				}
				if (!this.agreement) {
					uni.showToast({
						icon: 'none',
						title: '请先同意服务协议'
					})
					return
				}
				if (this.target === 2) {
					this.show = true
				} else {
					this.payment()
				}
			},
			payment(form = {}) {
				// 合并参数
				let data = {
					type: this.target,
					money: this.vipPrice,
					// money: parseFloat(this.showInfo.vip_price),
					vip_id: this.showInfo.id,
					integral: this.integralNum,
					...form
				}
				if (this.vipCoupon) {
					data.my_vip_coupon_id = this.vipCoupon.id
				}
				openVipApi(data).then(({
					data,
					code
				}) => {
					if (code === 200) {
						uni.requestPayment({
							provider: 'wxpay',
							...data.payRes,
							success: (res) => {
								uni.showToast({
									icon: 'success',
									title: '开通成功'
								})
								setTimeout(() => {
									this.setUserInfo()
									this.getData()
								}, 1000)
							}
						})
					}
				})
			},
			recive(data) {
				reciveCouponApi({
					coupon_id: data.id
				}).then(res => {
					if (res.code === 200) {
						this.showRecive = true
						this.getData()
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
					}
				})
			},
			// 打开权益详情页
			openDetail(data) {
				uni.navigateTo({
					url: `../mine/legal/legal?type=${this.current}&id=${data.id}`
				})
			}
		},
		onShareAppMessage() {
			return {
				title: '美国奥特莱斯官方授权商城', // 分享名称
				imageUrl: 'https://shop.outletds.com/img/share.png',
				path: 'pages/tabs/memberIntro/memberIntro', // 点击分享后的链接要来到的页面的路径已经对应需要的参数
				success: function(res) {
					// 分享成功之后的操作
					console.log("分享成功:" + JSON.stringify(res));
				},
				fail: function(res) {
					// 分享失败之后的操作
					console.log("分享失败:" + JSON.stringify(res));
				},
			};
		}
	}
</script>
<style scoped lang="scss">
	@import 'index.scss';
</style>